package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.service.ILabinfoSampleDataService;

/**
 * 样本信息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-07-03
 */
@Service
public class LabinfoSampleDataServiceImpl implements ILabinfoSampleDataService
{
    private static final Logger log = LoggerFactory.getLogger(LabinfoSampleDataServiceImpl.class);

    @Autowired
    private LabinfoSampleDataMapper labinfoSampleDataMapper;

    @Autowired
    private SampleCustomMapper sampleCustomMapper;

    @Autowired
    private SampleStaffMapper sampleStaffMapper;

    @Autowired
    private SampleAdminMapper sampleAdminMapper;

    /**
     * 查询样本信息
     *
     * @param id 样本信息主键
     * @return 样本信息
     */
    @Override
    public LabinfoSampleData selectLabinfoSampleDataById(Long id)
    {
        return labinfoSampleDataMapper.selectLabinfoSampleDataById(id);
    }

    /**
     * 查询样本信息列表
     *
     * @param labinfoSampleData 样本信息
     * @return 样本信息
     */
    @Override
    public List<LabinfoSampleData> selectLabinfoSampleDataList(LabinfoSampleData labinfoSampleData)
    {
        return labinfoSampleDataMapper.selectLabinfoSampleDataList(labinfoSampleData);
    }

    /**
     * 新增样本信息
     *
     * @param labinfoSampleData 样本信息
     * @return 结果
     */
    @Override
    public int insertLabinfoSampleData(LabinfoSampleData labinfoSampleData)
    {
        labinfoSampleData.setCreateTime(DateUtils.getNowDate());
        return labinfoSampleDataMapper.insertLabinfoSampleData(labinfoSampleData);
    }

    /**
     * 修改样本信息
     *
     * @param labinfoSampleData 样本信息
     * @return 结果
     */
    @Override
    public int updateLabinfoSampleData(LabinfoSampleData labinfoSampleData)
    {
        labinfoSampleData.setUpdateTime(DateUtils.getNowDate());
        return labinfoSampleDataMapper.updateLabinfoSampleData(labinfoSampleData);
    }

    /**
     * 批量删除样本信息
     *
     * @param ids 需要删除的样本信息主键
     * @return 结果
     */
    @Override
    public int deleteLabinfoSampleDataByIds(Long[] ids)
    {
        return labinfoSampleDataMapper.deleteLabinfoSampleDataByIds(ids);
    }

    /**
     * 删除样本信息信息
     *
     * @param id 样本信息主键
     * @return 结果
     */
    @Override
    public int deleteLabinfoSampleDataById(Long id)
    {
        return labinfoSampleDataMapper.deleteLabinfoSampleDataById(id);
    }

    @Override
    public List<Map> getReceiveSampleDateList(Map map) {
        String sjdwName = map.get("sjdwName")== null?"": map.get("sjdwName").toString();
        String patientPhone = map.get("patientPhone")== null?"": map.get("patientPhone").toString();
        return labinfoSampleDataMapper.getReceiveSampleDateList(sjdwName,patientPhone);
    }

    @Override
    public List<LabinfoSampleData> getSampleList(Map map) {
        String sjdwName = map.get("sjdwName")== null?"": map.get("sjdwName").toString();
        String patientPhone = map.get("patientPhone")== null?"": map.get("patientPhone").toString();
        String getSampleDate = map.get("getSampleDate")== null?"": map.get("getSampleDate").toString();
        String sampleDecWay = map.get("sampleDecWay")== null?"": map.get("sampleDecWay").toString();
        return labinfoSampleDataMapper.getSampleList(sjdwName,patientPhone,getSampleDate,sampleDecWay);
    }

    @Override
    public List<LabinfoSampleData> getSampleListBySampleSerialNumber(String sampleSerialNumber) {
        return labinfoSampleDataMapper.getSampleListBySampleSerialNumber(sampleSerialNumber);
    }

    @Override
    public List<Map> getSampleListBySampleDecWay(LabinfoSampleData labinfoSampleData, SysUser sysUser) {
        List<Map> itemList = new ArrayList<>();
        String sampleDecWay = labinfoSampleData.getSampleDecWay();
        String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
        Long deptId = sysUser.getDeptId();
        Long sharedId = sysUser.getUserId(); //获取当前登录用户的id，被分享人
        String searchValue = labinfoSampleData.getSearchValue();
        if(deptId != null){
            itemList = labinfoSampleDataMapper.getSampleListBySampleDecWay(sampleDecWay,sjys,deptId,String.valueOf(sharedId),searchValue);
        }
        return itemList;
    }

    @Override
    public int shareSamples(LabinfoSampleData labinfoSampleData) {
        if(labinfoSampleData.getDeptId()!=null && StringUtils.isNotEmpty(labinfoSampleData.getSharedId())
                && labinfoSampleData.getIds()!=null && labinfoSampleData.getIds().length > 0){
            Long[] ids = labinfoSampleData.getIds();
            for(int i = 0 ; i< ids.length ; i++){
                Long id = ids[i];
                //根据id获取item数据
                LabinfoSampleData query = new LabinfoSampleData();
                LabinfoSampleData returnLabinfoSampleData = labinfoSampleDataMapper.selectLabinfoSampleDataById(id);
                if(returnLabinfoSampleData != null){
                    query.setSharedId(labinfoSampleData.getSharedId());
                }
                query.setId(ids[i]);
                query.setIsShare("1");
                query.setDeptId(labinfoSampleData.getDeptId());
                labinfoSampleDataMapper.updateLabinfoSampleData(query);
            }
            return labinfoSampleData.getIds().length;
        }else{
            return 0;
        }

    }



    @Override
    public List<Map> getLabinfoSampleDataList(LabinfoSampleData labinfoSampleData,Boolean isAdmin) {
        List<Map> list = new ArrayList<>();
        if(isAdmin){ //是管理员
            list = labinfoSampleDataMapper.getLabinfoSampleDataListAdmin(labinfoSampleData);
        }else {
            list = labinfoSampleDataMapper.getLabinfoSampleDataList(labinfoSampleData);
        }
        return list;
    }


    @Override
    public AjaxResult saveSample(List<LabinfoSampleData> sampleDataList) {
        String failureMsg = "";
        List<LabinfoSampleData> errorList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(sampleDataList)){
            try {
                for (LabinfoSampleData labinfoSampleData : sampleDataList) {
                    String sampleSerialNumber = labinfoSampleData.getSampleSerialNumber();
                    String sampleId = labinfoSampleData.getSampleId();
                    if (StringUtils.isNotEmpty(sampleSerialNumber) && StringUtils.isNotEmpty(sampleId)) {
                        //根据outId查询id
                        Long id = labinfoSampleDataMapper.selectIdBySampleSerialNumberAndSampleId(sampleSerialNumber, sampleId);
                        if (id != null) { // 存在则更新
                            labinfoSampleData.setId(id);
                            labinfoSampleData.setUpdateTime(new Date());
                            labinfoSampleDataMapper.updateLabinfoSampleData(labinfoSampleData);
                        } else {
                            labinfoSampleData.setId(null);
                            labinfoSampleData.setCreateTime(new Date());
                            labinfoSampleDataMapper.insertLabinfoSampleData(labinfoSampleData);
                        }
                    } else {
                        errorList.add(labinfoSampleData);
                        failureMsg = "送检单编号和样本编号都不能为空";
                    }
                }
            }catch (Exception e){
                failureMsg = e.getMessage();
                log.error(e.getMessage());
                return AjaxResult.error(failureMsg);
            }
        }
        if(CollectionUtil.isNotEmpty(errorList)){
            return  AjaxResult.error(failureMsg,errorList);
        }
        return  AjaxResult.success("sample数据传输成功");
    }

    //用户导出
    @Override
    public List<SampleCustom> exportSampleCustom(LabinfoSampleData labinfoSampleData,SysUser sysUser) {
        String sampleDecWay = labinfoSampleData.getSampleDecWay();
        String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
        Long deptId = sysUser.getDeptId();
        Long sharedId = sysUser.getUserId(); //获取当前登录用户的id，被分享人
        List<SampleCustom> sampleCustomList = sampleCustomMapper.exportSampleCustom(sampleDecWay,sjys,deptId,String.valueOf(sharedId));
        return sampleCustomList;
    }

    @Override
    public List<SampleStaff> exportSampleStaff(LabinfoSampleData labinfoSampleData, SysUser sysUser) {
        String sampleDecWay = labinfoSampleData.getSampleDecWay();
        List<SampleStaff> sampleStaffList = sampleStaffMapper.exportSampleStaff(sampleDecWay);
        return sampleStaffList;
    }

    @Override
    public List<SampleAdmin> exportSampleAdmin(LabinfoSampleData labinfoSampleData, SysUser sysUser) {
        String sampleDecWay = labinfoSampleData.getSampleDecWay();
        List<SampleAdmin> sampleAdminList = sampleAdminMapper.exportSampleAdmin(sampleDecWay);
        return sampleAdminList;
    }

    @Override
    public List<LabinfoSampleData> getSampleListByList(List<String> sampleSerialNumberList) {
        return labinfoSampleDataMapper.getSampleListByList(sampleSerialNumberList);
    }

    @Override
    public List<Map> exportDataList(List<PageFieldUser> pageFieldUserList, LabinfoSampleData labinfoSampleData,SysUser sysUser) {
        List<Map> dataList = new ArrayList<>();
        StringBuilder stringBuilderFrom = new StringBuilder("select ");
        for(int i = 0;i < pageFieldUserList.size();i++ ){
            PageFieldUser pageFieldUser = pageFieldUserList.get(i);
            if(pageFieldUser != null && StringUtils.isNotEmpty(pageFieldUser.getFieldName()) && StringUtils.isNotEmpty(pageFieldUser.getFieldNameCn())){
                String fieldName = pageFieldUser.getFieldName();
                stringBuilderFrom.append(fieldName);
                if(i < pageFieldUserList.size()-1){
                    stringBuilderFrom.append(",");
                }
            }
        }
        String isRegister = sysUser.getIsRegister() == null? "0":sysUser.getIsRegister() ;//是否注册 1已注册，0未注册
        String sampleDecWay = labinfoSampleData.getSampleDecWay();
        if(StringUtils.isNotEmpty(isRegister) && isRegister.equals("1")) {//注册，则代表客户
            String sjys = sysUser.getNickName(); //获取当前登录用户的真实姓名,送检医生
            Long deptId = sysUser.getDeptId();
            Long sharedId = sysUser.getUserId(); //获取当前登录用户的id，被分享人
            dataList = labinfoSampleDataMapper.exportSampleCustom(stringBuilderFrom.toString(),sampleDecWay,sjys,deptId,String.valueOf(sharedId));
        }else {
            dataList = labinfoSampleDataMapper.exportSampleStaffOrAdmin(stringBuilderFrom.toString(),sampleDecWay);
        }
        return dataList;
    }
}
